package com.gopay.common.mq.converter;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.MessageConverter;

import javax.jms.*;
import java.io.Serializable;

/**
 * Json String <- -> 消息对象
 */
public class JsonMsgConverter<T extends Serializable> implements MessageConverter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private Class<T> msgClass ; //消息类型

    public JsonMsgConverter() {
    }

    public JsonMsgConverter(Class<T> msgClass) {
        this.msgClass = msgClass;
    }

    /**
     * Message --> 泛型T
     */
    @Override
    public T fromMessage(Message message) throws JMSException, MessageConversionException {
        if (logger.isDebugEnabled()) {
            logger.debug("Receive JMS message :" + message);
        }
        if (message instanceof TextMessage) {
            TextMessage textMessage = (TextMessage) message;
            return JSONObject.parseObject(textMessage.getText(), msgClass);
        } else {
            logger.error("Message:${} is not a instance of TextMessage." + message.toString());
            throw new JMSException( "Message:" + message.toString() + "is not a instance of TextMessage." + message.toString());
        }
    }



    /**
     * 泛型T --> Message
     */
    @Override
    public Message toMessage(Object obj, Session session) throws JMSException, MessageConversionException {
        if (logger.isDebugEnabled()) {
            logger.debug("Convert object to JMS message:${}" + obj.toString());
        }

        TextMessage textMessage = session.createTextMessage();
        textMessage.setText(JSONObject.toJSONString(obj));

        return textMessage;

    }

}
